#!/usr/bin/env python

# 将 exonerate 的输出结果转化为正常的形式 

import argparse
import sys

parser = argparse.ArgumentParser(
    description='''对exonerate的输出结果进行整理为gff格式 用于后续读取整合augustus进行手动基因鉴定，
    用法:
    exonerate_gtf2gff.py -i homo.gtf -p query -o homo.gff3 -n 1
    由大天才于2021年7月7日创建于浙江农业大学''')

parser.add_argument('-i',
                help='必须给定，exonerate的输出结果')

parser.add_argument('-p',
                help='前缀，默认为query')

parser.add_argument('-o',
                help='必须给定，输出文件')

parser.add_argument('-n',
                help='起始编号，默认为1')

args = parser.parse_args()

if not args.i or not args.o:
    parser.print_help()
    sys.exit()



infile = args.i
outfile = args.o


if not args.p:
    prefix = r'query'
else:
    prefix = args.p

if not args.n:
    n =1
else:
    n = int(args.n)

outhandle = open(outfile,'w')

outhandle.write('##gff-version   3\n')

n = 1
e = 1
c = 1

def write_exonerate_line(l,des_lista,new_lista,outhandle):
	'''
	l 分片的行
	des_lista 属性内容
	handle 写入文件
	'''

	for item in des_lista:

		item_lista = item.strip().split(' ')

		if len(item_lista)>=2 and item_lista[0] not in ['gene_id']:

			new_lista.append(item_lista[0]+'='+item_lista[1]) 


	l = l[:8] + [';'.join(new_lista)]

	outhandle.write('\t'.join(l)+'\n')



gene_name = ''

with open(infile) as fila:

	for i in fila:

		k = i.strip().split('#')[0].strip()
		if k!='':
			l = k.split('\t')
			if len(l) > 7:


				if len(l) > 8:
					des_lista = l[8].split(';')
				else:
					des_lista = []

				new_lista = []

				l[1] = 'exonerate'

				# 每个元件的属性
				pop = {}

				for t in des_lista:
					tt = t.strip().split(' ')

					if len(tt)>=2:
						pop[tt[0].strip()] =' '.join(tt[1:])

				if l[2] == 'gene':

					gene_id = prefix+'.gene'+str(n)

					if 'sequence' in pop:

						gene_name = pop['sequence']
					else:
						gene_name = gene_id

					ID = gene_id

					e = 1
					c = 1

					n += 1

					new_lista.append('ID='+ID)
					new_lista.append('Name='+gene_name)

					write_exonerate_line(l,des_lista,new_lista,outhandle)

					new_lista = []

					mRNA_id = gene_id+'.mRNA1'

					if 'sequence' in pop:

						mRNA_name = pop['sequence']+'.mRNA1'
					else:
						mRNA_name = mRNA_id

					ID = mRNA_id
					l[2] = 'mRNA'


					new_lista.append('ID='+ID)
					new_lista.append('Name='+mRNA_name)
					new_lista.append('Parent='+gene_id)
					
					write_exonerate_line(l,[],new_lista,outhandle)


				elif l[2] == 'exon':

					name = mRNA_name + '.exon' + str(e)

					ID = mRNA_id + '.exon' + str(e)

					e += 1

					new_lista.append('ID='+ID)
					new_lista.append('Name='+name)

					new_lista.append('Parent='+mRNA_id)

					write_exonerate_line(l,[],new_lista,outhandle)

				elif l[2] == 'cds':


					name = mRNA_name + '.CDS' + str(c)
					ID = mRNA_id + '.CDS' + str(e)

					l[2] = 'CDS'


					c += 1

					new_lista.append('ID='+ID)
					new_lista.append('Name='+name)

					new_lista.append('Parent='+mRNA_id)

					write_exonerate_line(l,[],new_lista,outhandle)


				else:


					continue


				# 	# 修改 描述项目




				

					
